/*
 * $Id: Lttp.cc,v 1.1 2005-09-07 03:20:25 bacon Exp $
 */

#include <xpp/net/Lttp.h>
#include <xp/bas/assert.h>

#define PUT_CHAR(x) if (put_char(x) == -1) return -1;

namespace xpp
{
	namespace net
	{
		using namespace xpp::bas;

		int Lttp::receiveLine (String* line)
		{
			xp_assert (line != NULL);

			p_errcode = ERR_NONE;
			receive_cancel_requested = false;

			String& l = *line;
			l = XP_TEXT("");

			xp_char_t pchar = XP_CHAR('\0');

			for (;;) {
				if (get_char() == -1) return -1;

				if (sttp_curc == XP_CHAR('\n')) {
					if (pchar == XP_CHAR('\r'))  
						l.remove (l.length() - 1, 1);
					break;
				}
				
				l.append (sttp_curc);
				if (max_line_len > 0 && l.length() > max_line_len) {
					p_errcode = ERR_TOOLONGLINE;
					return -1;
				}
				pchar = sttp_curc;	
			}

			return 0;
		}
		
		int Lttp::sendLine (const xp_char_t* line)
		{
			const xp_char_t* p = line;

			while (*p != XP_CHAR('\0')) {
				PUT_CHAR(*p);
				p++;
			}

			PUT_CHAR (XP_CHAR('\r'));
			PUT_CHAR (XP_CHAR('\n'));

			return flush_outbuf ();
		}

		int Lttp::sendLine (const xp_char_t* line, xp_size_t len)
		{
			const xp_char_t* p = line;
			const xp_char_t* end = line + len;

			while (p < end) {
				PUT_CHAR(*p);
				p++;
			}

			PUT_CHAR (XP_CHAR('\r'));
			PUT_CHAR (XP_CHAR('\n'));

			return flush_outbuf ();
		}

		const xp_char_t* Lttp::errorStr () const
		{
			switch (p_errcode) {
			case ERR_TOOLONGLINE:
				return XP_TEXT("line too long");
			default:
				return SttpBase::errorStr ();
			}
		}

	}
}
